package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
/**
 * @return 13141
 * 2025/7/8
 * 20:53
 */
@Controller
@RequestMapping("/main")
public class ChangePwdController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChangePwdController.class);
    @Resource
    private SysUserService sysUserService;
    //    根据 oldPassword 检验旧密码
    @ResponseBody
    @GetMapping("/oldPasswordCheck")
    public String accountExist(@RequestParam("oldPassword") String oldPassword) {
        LOGGER.debug("检查旧密码 oldPassword={}旧密码是否正确是否存在", oldPassword);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(oldPassword)) {
            resultMap.put("pass", 0);
        } else {
            try {
                // 获取登录用户
                SysUser loginUser = session(Constants.SESSION_USER);
                boolean ok = sysUserService.checkOldPassword(loginUser.getId(), oldPassword);
                if (ok) {
//                    已经存在，设置为1
                    resultMap.put("pass", 1);
                } else {
                    resultMap.put("pass", 0);
                }
            } catch (Exception e) {
                LOGGER.error("ChangePwdController 中的" + "oldPassword方法执行出现错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }
    // 跳转 changePwd.jsp页面
    @GetMapping("/changePwd")
    public String toChangePwd() {
        return "sys/changePwd";
    }
    // 点击提交更改密码
    @PostMapping("/changePwd")
    public String doChangePwd(@RequestParam("password") String password, Model model) {
        try {
            SysUser loginUser = session(Constants.SESSION_USER);
            boolean ok = sysUserService.updatePwd(loginUser.getId(), password);
            model.addAttribute("password", password);
            if (ok) {
                return redirect("/login");
            }
        } catch (Exception error) {
            LOGGER.error("ChangePwdController 中的 doChangePwd()方法出现错误", error);
            throw new RuntimeException(error);
        }
        return "sys/changePwd";
    }
}
